﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using NetCoreCMS.PayAPI.tenpaypc;

namespace NetCoreCMS.Web.Areas.Payments.Controllers
{
    public class TenpayPCController : AreasController
    {
        public IUser_rechargeService _user_recharge { get; set; }
        public IOrdersService _orders { get; set; }
        public ISite_paymentService _site_payment { get; set; }
        public IPaymentService _payment { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        private IHttpContextAccessor _accessor { get; set; }
        public IActionResult Index()
        {
            int site_payment_id = 0; //订单支付方式

            //=============================获得订单信息================================
            string order_no = CMSRequest.GetFormString("pay_order_no",HttpContext).ToUpper(); //订单号
            decimal order_amount = CMSRequest.GetFormDecimal("pay_order_amount", 0, HttpContext); //订单金额
            string user_name = CMSRequest.GetFormString("pay_user_name", HttpContext); //支付用户名
            string subject = CMSRequest.GetFormString("pay_subject", HttpContext); //备注说明
            string trans_type = string.Empty; //交易类型1实物2虚拟

            if (order_no == "" || order_amount == 0)
            {
                return ToError("对不起，您提交的参数有误！");
            }
            if (order_no.StartsWith("R")) //R开头为在线充值订单
            {
                User_recharge model = _user_recharge.GetModel(order_no);
                if (model == null)
                {
                    return ToError("对不起，您充值的订单号不存在或已删除！");        
                }
                if (model.amount != order_amount)
                {
                    return ToError("对不起，您充值的订单金额与实际金额不一致！");     
                }
                trans_type = "2";
                site_payment_id = model.payment_id; //站点支付方式ID
            }
            else //B开头为商品订单
            {
                Orders model = _orders.GetModel(order_no);
                if (model == null)
                {
                    return ToError("对不起，您支付的订单号不存在或已删除！");         
                }
                if (model.order_amount != order_amount)
                {
                    return ToError("对不起，您支付的订单金额与实际金额不一致！"); 
                }
                trans_type = "1";
                site_payment_id = model.payment_id; //站点支付方式ID
            }
            //检查会员还是匿名
            if (!string.IsNullOrEmpty(user_name))
            {
                user_name = "支付会员：" + user_name;
            }
            else
            {
                user_name = "匿名用户";
            }
            var site_paymentModel = _site_payment.GetList().FirstOrDefault(a => a.payment_id == site_payment_id);
            var paymentModel = _payment.GetModel(site_payment_id);
            //===============================请求参数==================================
            TenpayUtil config = new TenpayUtil(site_paymentModel, paymentModel, sysConfig, HttpContext);
            //创建RequestHandler实例
            RequestHandler reqHandler = new RequestHandler(HttpContext);
            //初始化
            reqHandler.init();
            //设置密钥
            reqHandler.setKey(config.key);
            reqHandler.setGateUrl("https://gw.tenpay.com/gateway/pay.htm");
            //-----------------------------
            //设置支付参数
            //-----------------------------
            reqHandler.setParameter("partner", config.partner); //商户号
            reqHandler.setParameter("out_trade_no", order_no); //商家订单号
            reqHandler.setParameter("total_fee", (Convert.ToDouble(order_amount) * 100).ToString()); //商品金额,以分为单位
            reqHandler.setParameter("return_url", config.return_url); //交易完成后跳转的URL
            reqHandler.setParameter("notify_url", config.notify_url); //接收财付通通知的URL
            reqHandler.setParameter("body", user_name); //商品描述
            reqHandler.setParameter("bank_type", "DEFAULT"); //银行类型(中介担保时此参数无效)
            reqHandler.setParameter("spbill_create_ip", _accessor.HttpContext.Connection.RemoteIpAddress.ToString()); //用户的公网ip，不是商户服务器IP
            reqHandler.setParameter("fee_type", "1");  //币种，1人民币
            reqHandler.setParameter("subject", sysConfig.webname + "-" + subject); //商品名称(中介交易时必填)

            //系统可选参数
            reqHandler.setParameter("sign_type", "MD5");
            reqHandler.setParameter("service_version", "1.0");
            reqHandler.setParameter("input_charset", "UTF-8");
            reqHandler.setParameter("sign_key_index", "1");

            //业务可选参数
            reqHandler.setParameter("product_fee", "0");                 //商品费用，必须保证transport_fee + product_fee=total_fee
            reqHandler.setParameter("transport_fee", "0");               //物流费用，必须保证transport_fee + product_fee=total_fee
            reqHandler.setParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));            //订单生成时间，格式为yyyymmddhhmmss
            reqHandler.setParameter("time_expire", "");                 //订单失效时间，格式为yyyymmddhhmmss
            reqHandler.setParameter("buyer_id", "");                    //买方财付通账号
            reqHandler.setParameter("goods_tag", "");                   //商品标记
            reqHandler.setParameter("trade_mode", "1");     //交易模式，1即时到账(默认)，2中介担保，3后台选择（买家进支付中心列表选择）
            reqHandler.setParameter("transport_desc", "");              //物流说明
            reqHandler.setParameter("trans_type", "1");                  //交易类型，1实物交易，2虚拟交易
            reqHandler.setParameter("agentid", "");                     //平台ID
            reqHandler.setParameter("agent_type", "");                  //代理模式，0无代理(默认)，1表示卡易售模式，2表示网店模式
            reqHandler.setParameter("seller_id", "");                   //卖家商户号，为空则等同于partner

            //获取请求带参数的url
            string requestUrl = reqHandler.getRequestURL();

            //实现自动跳转===============================
            StringBuilder sbHtml = new StringBuilder();
            sbHtml.Append("<form id='tenpaysubmit' name='tenpaysubmit' action='" + reqHandler.getGateUrl() + "' method='get'>");
            Hashtable ht = reqHandler.getAllParameters();
            foreach (DictionaryEntry de in ht)
            {
                sbHtml.Append("<input type=\"hidden\" name=\"" + de.Key + "\" value=\"" + de.Value + "\" >\n");
            }
            //submit按钮控件请不要含有name属性
            sbHtml.Append("<input type='submit' value='确认' style='display:none;'></form>");
            sbHtml.Append("<script>document.forms['tenpaysubmit'].submit();</script>");

            return Content(sbHtml.ToString());
        }
        public IActionResult Notify_Url()
        {
            int site_payment_id = 0; //站点支付方式ID
            ResponseHandler resHandler = new ResponseHandler(HttpContext); //创建ResponseHandler实例
            string order_no = resHandler.getParameter("out_trade_no").ToUpper(); //商户订单号
            string trade_no = resHandler.getParameter("transaction_id"); //财付通订单号
            string total_fee = resHandler.getParameter("total_fee"); //金额,以分为单位
            string discount = resHandler.getParameter("discount"); //如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
            string trade_state = resHandler.getParameter("trade_state"); //支付结果
            if (order_no.StartsWith("R")) //充值订单
            {
                site_payment_id = _user_recharge.GetModel(order_no).payment_id;
            }
            else if (order_no.StartsWith("B")) //商品订单
            {
                site_payment_id = _orders.GetModel(order_no).payment_id;
            }
            if (site_payment_id == 0)
            {
                return Content("该订单号不存在");
            }
            var site_paymentModel = _site_payment.GetList().FirstOrDefault(a => a.payment_id == site_payment_id);
            var paymentModel = _payment.GetModel(site_payment_id);
            //找到站点支付方式ID开始验证
            TenpayUtil config = new TenpayUtil(site_paymentModel, paymentModel, sysConfig, HttpContext);
            resHandler.setKey(config.key);
            //判断签名
            if (resHandler.isTenpaySign())
            {
                string notify_id = resHandler.getParameter("notify_id"); //通知id
                RequestHandler queryReq = new RequestHandler(HttpContext); //通过通知ID查询，确保通知来至财付通
                queryReq.init();
                queryReq.setKey(config.key);
                queryReq.setGateUrl("https://gw.tenpay.com/gateway/simpleverifynotifyid.xml");
                queryReq.setParameter("partner", config.partner);
                queryReq.setParameter("notify_id", notify_id);

                //通信对象
                TenpayHttpClient httpClient = new TenpayHttpClient();
                httpClient.setTimeOut(5);
                //设置请求内容
                httpClient.setReqContent(queryReq.getRequestURL());
                //后台调用
                if (httpClient.call())
                {
                    //设置结果参数
                    ClientResponseHandler queryRes = new ClientResponseHandler();
                    queryRes.setContent(httpClient.getResContent());
                    queryRes.setKey(config.key);
                    //判断签名及结果
                    //只有签名正确,retcode为0，trade_state为0才是支付成功
                    if (queryRes.isTenpaySign())
                    {
                        //判断签名及结果
                        if ("0".Equals(queryRes.getParameter("retcode")))
                        {
                            #region 即时到账处理方法====================================
                            if ("0".Equals(trade_state))
                            {
                                if (order_no.StartsWith("R")) //充值订单
                                {
                                    User_recharge model = _user_recharge.GetModel(order_no);
                                    if (model == null)
                                    {
                                        return Content("该订单号不存在");
                                    }
                                    if (model.status == 1) //已成功
                                    {
                                        return Content("success");
                                    }
                                    if (model.amount != (decimal.Parse(total_fee) / 100))
                                    {
                                        return Content("订单金额和支付金额不相符");
                                    }
                                    bool result = _user_recharge.Confirm(order_no);
                                    if (!result)
                                    {
                                        return Content("修改订单状态失败");
                                    }
                                }
                                else if (order_no.StartsWith("B")) //商品订单
                                {
                                    Orders model = _orders.GetModel(order_no);
                                    if (model == null)
                                    {
                                        return Content("该订单号不存在");
                                    }
                                    if (model.payment_status == 2) //已付款
                                    {
                                        return Content("success");
                                    }
                                    if (model.order_amount != (decimal.Parse(total_fee) / 100))
                                    {
                                        return Content("订单金额和支付金额不相符");
                                    }
                                    bool result = _orders.UpdateField(order_no, "trade_no='" + trade_no + "',status=2,payment_status=2,payment_time='" + DateTime.Now + "'");
                                    if (!result)
                                    {
                                        return Content("修改订单状态失败");
                                    }
                                    //扣除积分
                                    if (model.point < 0)
                                    {
                                        _user_point_log.Add(model.user_id, model.user_name, model.point, "换购扣除积分，订单号：" + model.order_no, false);
                                    }
                                }
                                //给财付通系统发送成功信息，财付通系统收到此结果后不再进行后续通知
                                return Content("success");
                            }
                            else
                            {
                                return Content("即时到账支付失败");
                            }
                            #endregion
                        }
                        else
                        {
                            return Content("查询验证签名失败或id验证失败");
                        }
                    }
                    else
                    {
                        return Content("通知ID查询签名验证失败");
                    }
                }
                else
                {
                    return Content("后台调用通信失败");
                }
            }
            else
            {
                return Content("签名验证失败");
            }
        }
        public IActionResult Return_Url()
        {
            int site_payment_id = 0; //站点支付方式ID
            ResponseHandler resHandler = new ResponseHandler(HttpContext); //创建ResponseHandler实例
            string notify_id = resHandler.getParameter("notify_id"); //通知id
            string out_trade_no = resHandler.getParameter("out_trade_no").ToUpper(); //商户订单号
            string transaction_id = resHandler.getParameter("transaction_id"); //财付通订单号
            string total_fee = resHandler.getParameter("total_fee"); //金额,以分为单位
            string discount = resHandler.getParameter("discount"); //如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
            string trade_state = resHandler.getParameter("trade_state"); //支付结果

            if (out_trade_no.StartsWith("R")) //充值订单
            {
                site_payment_id = _user_recharge.GetModel(out_trade_no).payment_id;
            }
            else if (out_trade_no.StartsWith("B")) //商品订单
            {
                site_payment_id = _orders.GetModel(out_trade_no).payment_id;
            }
            var site_paymentModel = _site_payment.GetList().FirstOrDefault(a => a.payment_id == site_payment_id);
            var paymentModel = _payment.GetModel(site_payment_id);
            //找到站点支付方式ID开始验证
            if (site_payment_id > 0)
            {
                TenpayUtil config = new TenpayUtil(site_paymentModel, paymentModel, sysConfig, HttpContext);
                resHandler.setKey(config.key);
                //判断签名
                if (resHandler.isTenpaySign())
                {
                    if ("0".Equals(trade_state))
                    {
                        //给财付通系统发送成功信息，财付通系统收到此结果后不再进行后续通知
                        return Redirect("/Web/Payment/Index?action=succeed&order_no=" + out_trade_no);
                    }
                }
            }
            //认证签名失败
            return Redirect("/Web/Payment/Index?action=error");
        }
    }
}